#include "common.h"
#include "server.h"
#include "Decryptor.h"

#ifdef DEBUG
#define KEYFILE "localkeys/carrier.pem"
#else
#define KEYFILE "realkeys/carrier.pem"
#endif

#define PASSWORD "password"

void handle_connection(SSL *ssl, int s);

Decryptor* myDecryptor = NULL;

int main(int argc, char **argv) {
	SSLServer* server = new SSLServer(KEYFILE, PASSWORD, CARRIER_SERVER_PORT,
			handle_connection);

	myDecryptor = new Decryptor(CARRIER_PRIV_KEY);
	server->WaitForConnection();
	exit(0);
}

void handle_connection(SSL *ssl, int s) {
	int decrypted_size;
	unsigned char* buf;
	struct ShippingInfo* decryptedData;
	uint32_t enc_pkt_size;

	printf("new connection\r\n");

	// get size of entire EVP packet
	SSL_read_until_full(ssl, &enc_pkt_size, sizeof(uint32_t));
	enc_pkt_size = ntohl(enc_pkt_size);
	buf = new unsigned char[enc_pkt_size];

	// read and decrypt EVP packet
	SSL_read_until_full(ssl, buf, enc_pkt_size);

#ifndef NOENCRYPT
	decryptedData = (struct ShippingInfo*) (void*) myDecryptor->DecryptPacket(
			buf, enc_pkt_size, &decrypted_size);
	delete[] buf;

	// verify digests ----
	unsigned int si_digest_len = 0;
	unsigned char* si_str = prep_for_digest(*decryptedData);
	unsigned char* si_digest = sha1_digest(si_str, strlen((char*) si_str) + 1,
			&si_digest_len);

	int diff = strncmp((const char*) si_digest,
			(const char*) decryptedData->message_digest, si_digest_len);
	if (diff != 0) {
		printf("Error: inconsistent SI digests.\n");
		return;
	}

	delete[] si_str;
	delete[] si_digest;
#else
	decryptedData = (struct ShippingInfo*)(void*)buf;
	decrypted_size = enc_pkt_size;
#endif

	//	printf("Ship to:\n %s\n", decryptedData->shipping_addr);

	delete decryptedData;

	SSL_write(ssl, ACK_STRING, sizeof(ACK_STRING));
}
